from rest_framework import serializers

from goods.models import SKU


class CartSerializer(serializers.Serializer):
    """购物车添加和修改序列化器"""
    selected = serializers.BooleanField(label='是否勾选',default=True)
    count = serializers.IntegerField(label='商品数量')
    sku_id = serializers.IntegerField(label='商品id')

    def validate(self, attrs):
        # 校验商品是否存在
        sku_id = attrs['sku_id']
        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            raise serializers.ValidationError('商品不存在')

        # 校验商品库存是否足够
        count = attrs['count']
        stock = sku.stock
        if count > stock:
            raise serializers.ValidationError('商品库存不足')
        return attrs
class CartGetSerializer(serializers.ModelSerializer):
    """购物车记录获取(商品)序列化器"""
    count = serializers.IntegerField(label='商品数量')
    selected = serializers.BooleanField(label='勾选')

    class Meta:
        model = SKU
        fields = ('id','name','price','default_image_url','count','selected')

class CartDeleteSerializer(serializers.Serializer):
    sku_id = serializers.IntegerField(label='商品id')

    def validate_sku_id(self,value):
        """校验商品是否存在"""
        try:
            sku = SKU.objects.get(id = value)
        except Exception:
            raise serializers.ValidationError('商品不存在')
        return value

class CartSelectSerializer(serializers.Serializer):
    """购物车全选与否序列化器"""
    selected = serializers.BooleanField(label='是否全选中')


